import dayjs from "dayjs";
import { ref, reactive, h, onMounted, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { hasAuth } from "@/router/utils";

import {
  getDictionary,
  dictionaryAdd,
  dictionaryUpdate,
  dictionaryDelete
} from "@/api/basicArchives/dictionaries";

export function useDictionar() {
  const form = reactive({
    name: undefined
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 100,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand"
    },
    {
      label: "名称",
      prop: "dictionaryName"
    },
    {
      label: "编码",
      prop: "dictionaryCode"
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "键",
      prop: "itemName"
    },
    {
      label: "值",
      prop: "itemValue"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getDictionary(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    localStorage.setItem("dictList", JSON.stringify(data.records));

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const formRef = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}数据字典`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          dictionaryName: row?.dictionaryName ?? undefined,
          dictionaryCode: row?.dictionaryCode ?? undefined,
          itemList: row?.itemList ?? []
        }
      },
      width: "1000px",
      draggable: true,
      sureBtnLoading: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            if (title === "新增") {
              // 表单规则校验通过
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await dictionaryAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await dictionaryUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  async function handleDelete(row) {
    const res = await dictionaryDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  const itemColumns: TableColumnList = [
    {
      label: "键",
      prop: "itemName",
      cellRenderer: ({ row }) => <el-input clearable v-model={row.itemName} />
    },
    {
      label: "值",
      prop: "itemValue",
      cellRenderer: ({ row }) => <el-input clearable v-model={row.itemValue} />
    },
    {
      label: "操作",
      fixed: "right",
      width: 90,
      slot: "operation"
    }
  ];

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    columns,
    loading,
    dataList,
    pagination,
    resetForm,
    onSearch,
    openDialog,
    useRenderIcon,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    itemColumns,
    childColumns,
    hasAuth
  };
}
